import { useEffect, useState, useCallback } from 'react';
import { Popover } from 'antd-mobile';
import { useParams } from 'react-router-dom';
import { h5Utils as Core, tranferIcon, changeAmin, InbizIcon, getOfficialPreview, deepClone } from '@inbiz/utils';
import { useSiteContent } from '@inbiz/render';
import { useInbizRouter } from '@inbiz/hooks';
import { menuTreeList } from '../service';
import { TextWidget } from '@inbiz/react';
import './index.less';

interface IconType {
  type: string;
  size: number;
  color: string;
}

interface InbizMenuProps {
  inbiz: any;
  isAmin: boolean;
}

export const InbizMenu = (props: InbizMenuProps) => {
  const { inbiz, isAmin } = props;

  const bgColor = 'var(--inbiz-color-menu-top-bg)';
  const bgHoverColor = 'var(--inbiz-color-menu-top-bg-selected)';
  const fontColor = 'var(--inbiz-color-menu-top-default)';
  const icoHoverColor = 'var(--inbiz-color-menu-top-selected)';
  const history = useInbizRouter();
  const siteContent = useSiteContent();
  // 菜单数据
  const [menuTree, $menuTree] = useState([]);
  // 刷新控制变量
  const [refresh, $refresh] = useState<number>(1);
  // 站点信息
  const appInfo = inbiz.appInfo;
  // 当前路由数据（会随路由变化而触发变化）
  const params: any = useParams();

  // 初始化数据
  useEffect(() => {
    getMenuTreeList(params);
  }, [params]);

  // 获取菜单数据
  const getMenuTreeList = useCallback(async (params: any) => {
    let res: any = [];
    if (getOfficialPreview() && appInfo.SiteInfo?.IsSkipMenuPerm) {
      let menu = deepClone(siteContent?.menuJson) || [];
      menu = menu.sort((item, item2) => item.Sort - item2.Sort)
      menu.forEach((item) => {
        if (item.ParentId == '') {
          res.push(item)
        }
      })
      res = res.map((item: any) => {
        item.Children = [];
        menu.forEach((menu) => {
          if (item.OutId === menu.ParentId) {
            item.Children.push(menu);
          };
        });
        return item
      });
    } else {
      res = await menuTreeList({
        siteOutId: appInfo.OutId,
        appId: appInfo.AppId,
        dataVersionId: getOfficialPreview() ? undefined : appInfo.DataVersionId,
      });
    }

    if (!res || res.error) {
      return;
    }
    if (res.length > 0) {
      res.forEach((item: any) => {
        if (
          item.Route === params.pageRouter ||
          (params.pageRouter === 'page' && item.Route === params.childRouter)
        ) {
          item.focus = true;
        }
        item.Children.forEach((entry: any) => {
          if (entry.Route === params.childRouter || entry.Route === params.pageRouter) {
            entry.focus = true;
            item.focus = true;
          }
          entry.oldRoute = entry.Route;
          entry.Route = `${item.Route}/${entry.Route}`;
          entry.ParentMenuId = item.OutId;
        });
      });
      $menuTree(res);
    }
  }, []);

  // 组合子菜单popover列表actions数据
  const getPopList = useCallback((Children: any) => {
    return Children.map((item: any) => {
      const icon: IconType = tranferIcon(item.Icon);
      return {
        text: (
          <span
            style={{
              color: item.focus ? icoHoverColor : fontColor,
              fontSize: 12,
            }}
          >
            <TextWidget>{item.DisplayName}</TextWidget>
          </span>
        ),
        menu: item,
        icon: icon?.type ? (
          <InbizIcon
            type={icon.type}
            style={{
              color: item.focus ? icoHoverColor : fontColor,
              fontSize: 16,
            }}
          />
        ) : null,
      };
    });
  }, []);

  // 点击菜单跳转
  const handleClick = useCallback((item: any) => {
    Core.handleClick(item, history);
    $refresh((pre) => pre + 1);
  }, []);

  useEffect(() => {
    changeAmin(isAmin);
  }, [isAmin]);

  return (
    <div className={'inbiz-menu-box'} style={{ backgroundColor: bgColor }} key={refresh}>
      {menuTree.map((item: any, i: number) => {
        if (i > 4) {
          return null;
        }
        const icon: IconType = tranferIcon(item.Icon);
        const _length = menuTree.length > 5 ? 5 : menuTree.length;
        return (
          <div
            key={item.OutId + i}
            className="inbiz-menu-item"
            style={{
              width: `${100 / _length}%`,
              backgroundColor: item.focus ? bgHoverColor : 'transparent',
            }}
          >
            {item.Children.length > 0 ? (
              // 有子菜单
              <Popover.Menu
                actions={getPopList(item.Children)}
                onAction={(node: any) => {
                  handleClick(node.menu);
                }}
                placement="top"
                trigger="click"
                className="inbiz-wap-menu-popover"
              >
                <div>
                  {icon?.type ? (
                    <InbizIcon
                      type={icon.type}
                      style={{
                        color: item.focus ? icoHoverColor : fontColor,
                        fontSize: 24,
                      }}
                    />
                  ) : null}
                  {item.DisplayName && (
                    <div
                      style={{
                        color: item.focus ? icoHoverColor : fontColor,
                      }}
                    >
                      <TextWidget>{item.DisplayName}</TextWidget>
                    </div>
                  )}
                </div>
              </Popover.Menu>
            ) : (
              // 无子菜单
              <div
                onClick={() => {
                  handleClick(item);
                }}
              >
                {icon?.type ? (
                  <InbizIcon
                    type={icon.type || 'icon-list'}
                    style={{
                      color: item.focus ? icoHoverColor : fontColor,
                      fontSize: 24,
                    }}
                  />
                ) : null}
                {item.DisplayName && (
                  <div
                    style={{
                      color: item.focus ? icoHoverColor : fontColor,
                    }}
                    className="inbiz-menu-item-text"
                  >
                    <TextWidget>{item.DisplayName}</TextWidget>
                  </div>
                )}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
};

export default InbizMenu
